package com.example.listener;
import com.alibaba.fastjson.JSONObject;
import com.example.dao.OrderMapper;
import com.example.microinvestcommon.entity.UserOrder;
import com.example.microinvestcommon.service.RedisService;
import com.example.service.UserTradeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OrderListener {

    private static final Logger logger = LoggerFactory.getLogger(OrderListener.class);
    private final UserTradeService userTradeService;
    private final OrderMapper orderMapper;
    private final RedisService redisService;

    @Autowired
    OrderListener(UserTradeService userTradeService,OrderMapper orderMapper,RedisService redisService){
        this.userTradeService=userTradeService;
        this.orderMapper=orderMapper;
        this.redisService=redisService;
    }

    //监听队列
    @RabbitListener(queues = "userBuyOrder.release.queue")
    public void listenBuyOrder(String buyOrderInfo){
        UserOrder userOrder= JSONObject.parseObject(buyOrderInfo,UserOrder.class);
        //判断redis中是否存在订单信息，如果不存在，说明用户已经撤单则返回不进行其他操作
        if(!redisService.isOrderIdExist(String.valueOf(userOrder.getOrderId()),String.valueOf(userOrder.getUserId()))) {
            logger.info("用户撤单");
            return;
        }
        //订单存在删除redis中订单信息，继续接下来操作
        redisService.removeOrderId(String.valueOf(userOrder.getOrderId()),String.valueOf(userOrder.getUserId()));
        userTradeService.addBuyTradeService(userOrder);
        orderMapper.orderStatusDone(userOrder.getOrderId());

    }

    @RabbitListener(queues = "userSellOrder.release.queue")
    public void listenSellOrder(String sellOrderInfo){
        //判断redis中是否存在订单信息，如果不存在，说明用户已经撤单则返回不进行其他操作
        UserOrder userOrder= JSONObject.parseObject(sellOrderInfo,UserOrder.class);
        if(!redisService.isOrderIdExist(String.valueOf(userOrder.getOrderId()),String.valueOf(userOrder.getUserId()))) {
            logger.info("用户撤单");
            return;
        }
        //订单存在删除redis中订单信息，继续接下来操作
        redisService.removeOrderId(String.valueOf(userOrder.getOrderId()),String.valueOf(userOrder.getUserId()));
        userTradeService.addSellTradeService(userOrder);
        orderMapper.orderStatusDone(userOrder.getOrderId());
    }


}
